<!DOCTYPE html>
<!-- 文件上传与显示页面 -->
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OCR 文字识别</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            text-align: center;
        }
        .upload-area {
            border: 2px dashed #ccc;
            padding: 20px;
            margin: 20px 0;
            border-radius: 5px;
        }
        #preview {
            max-width: 100%;
            margin: 10px 0;
        }
        #result {
            margin-top: 20px;
            text-align: left;
        }
        .confidence {
            color: #666;
            font-size: 0.9em;
        }
        .button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .text-output {
            width: 100%;
            min-height: 200px;
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            resize: vertical;
        }
        /* 添加优化按钮样式 */
        .optimize-button {
            background-color: #2196F3;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        .model-select {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            border: 1px solid #ccc;
        }
        /* 添加文本框样式 */
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            line-height: 1.5;
            resize: vertical;
        }
        
        textarea:focus {
            outline: none;
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        .progress {
            height: 25px;
            background-color: #f5f5f5;
            border-radius: 4px;
            box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
            overflow: hidden;
        }

        .progress-bar {
            height: 100%;
            background-color: #4CAF50;
            color: white;
            text-align: center;
            line-height: 25px;
            transition: width 0.3s ease;
        }

        /* 添加按钮禁用状态样式 */
        .button:disabled, .optimize-button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .button-container {
            position: relative;
            display: inline-block;
            margin: 4px 2px;
        }

        .button, .optimize-button {
            position: relative;
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s;
            width: 200px; /* 固定宽度 */
        }

        .optimize-button {
            background-color: #2196F3;
        }

        .button:disabled, .optimize-button:disabled {
            background-color: #cccccc;
        }

        .progress-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 4px; /* 细长的进度条 */
            background-color: rgba(255, 255, 255, 0.3);
            width: 100%;
            display: none;
        }

        .progress-bar {
            height: 100%;
            background-color: #ffffff;
            transition: width 0.3s ease;
        }

        .button-text {
            position: relative;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>OCR 文字识别系统</h1>
        <div class="upload-area">
            <input type="file" id="imageInput" accept="image/*">
            <p>支持的图片格式: JPG, PNG, BMP</p>
        </div>
        <div class="button-container">
            <button id="recognizeBtn" class="button" style="display: none;">
                <span class="button-text">开始识别</span>
                <div class="progress-overlay" id="recognizeProgress">
                    <div class="progress-bar" style="width: 0%"></div>
                </div>
            </button>
        </div>
        <img id="preview" style="display: none;">
        <div id="result"></div>
        <div class="form-group">
            <label for="outputText">识别结果：</label>
            <textarea id="outputText" 
                class="form-control" 
                rows="5" 
                placeholder="OCR识别结果将显示在这里..."></textarea>
        </div>
        <!-- 添加优化按钮和优化后的文本框 -->
        <select id="modelSelect" class="model-select" style="display: none;">
            <!-- 选项将通过 JavaScript 动态填充 -->
        </select>
        <textarea id="instructionText" 
            class="form-control" 
            rows="2" 
            style="display: none; margin: 10px 0;"
            placeholder="请输入优化建议，例如：将文本改写成正式的商务邮件格式">请帮助优化和完善以下文本，使其更加通顺、准确。</textarea>
        <div class="button-container">
            <button id="optimizeBtn" class="optimize-button" style="display: none;">
                <span class="button-text">优化文本</span>
                <div class="progress-overlay" id="optimizeProgress">
                    <div class="progress-bar" style="width: 0%"></div>
                </div>
            </button>
        </div>
        <textarea id="optimizedText" class="text-output" readonly placeholder="优化后的文本将显示在这里"></textarea>
    </div>

    <script>
        document.getElementById('imageInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            // 显示预览
            const preview = document.getElementById('preview');
            preview.style.display = 'block';
            preview.src = URL.createObjectURL(file);

            // 显示识别按钮
            document.getElementById('recognizeBtn').style.display = 'block';
        });

        // 进度条控制函数
        function updateButtonProgress(buttonId, progressId, percent) {
            const progressOverlay = document.getElementById(progressId);
            const progressBar = progressOverlay.querySelector('.progress-bar');
            const button = document.getElementById(buttonId);
            
            if (percent > 0) {
                progressOverlay.style.display = 'block';
            }
            
            progressBar.style.width = percent + '%';
            
            // 更新按钮文本
            const buttonText = button.querySelector('.button-text');
            buttonText.textContent = percent < 100 ? 
                `处理中 ${percent}%` : 
                (buttonId === 'recognizeBtn' ? '开始识别' : '优化文本');
                
            if (percent >= 100) {
                setTimeout(() => {
                    progressOverlay.style.display = 'none';
                    progressBar.style.width = '0%';
                }, 1000);
            }
        }

        // 修改识别按钮点击事件
        document.getElementById('recognizeBtn').addEventListener('click', async function() {
            const button = this;
            button.disabled = true;
            updateButtonProgress('recognizeBtn', 'recognizeProgress', 0);
            
            // 模拟进度
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress > 90) {
                    clearInterval(progressInterval);
                    progress = 90;
                }
                updateButtonProgress('recognizeBtn', 'recognizeProgress', Math.min(Math.round(progress), 90));
            }, 300);

            try {
                const file = document.getElementById('imageInput').files[0];
                if (!file) return;

                // 准备发送数据
                const formData = new FormData();
                formData.append('file', file);

                // 发送请求
                const response = await fetch('/ocr/', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                // 显示结果
                const resultDiv = document.getElementById('result');
                resultDiv.innerHTML = '<h2>识别结果：</h2>';
                
                let fullText = '';
                data.text.forEach((text, index) => {
                    const confidence = (data.confidence[index] * 100).toFixed(2);
                    resultDiv.innerHTML += `
                        <p>
                            ${text}
                            <span class="confidence">(置信度: ${confidence}%)</span>
                        </p>
                    `;
                    fullText += text + '\n';
                });

                // 更新文本框内容
                document.getElementById('outputText').value = fullText;
                // 显示优化按钮
                document.getElementById('optimizeBtn').style.display = 'block';
                // 清空优化文本框
                document.getElementById('optimizedText').value = '';

                // 完成时
                clearInterval(progressInterval);
                updateButtonProgress('recognizeBtn', 'recognizeProgress', 100);
            } catch (error) {
                clearInterval(progressInterval);
                updateButtonProgress('recognizeBtn', 'recognizeProgress', 0);
                console.error('Error:', error);
                alert('识别失败，请重试');
            } finally {
                button.disabled = false;
            }
        });

        // 获取可用模型列表
        async function loadModels() {
            try {
                const response = await fetch('/models');
                const data = await response.json();
                const select = document.getElementById('modelSelect');
                data.models.forEach(model => {
                    const option = document.createElement('option');
                    option.value = model;
                    option.textContent = model;
                    select.appendChild(option);
                });
            } catch (error) {
                console.error('Error loading models:', error);
            }
        }

        // 页面加载时获取模型列表
        loadModels();

        // 修改优化按钮的点击事件处理
        document.getElementById('optimizeBtn').addEventListener('click', async function() {
            const button = this;
            const originalText = document.getElementById('outputText').value;
            const selectedModel = document.getElementById('modelSelect').value;
            const instruction = document.getElementById('instructionText').value;
            
            if (!originalText) return;

            // 禁用按钮
            button.disabled = true;
            updateButtonProgress('optimizeBtn', 'optimizeProgress', 0);
            
            // 模拟进度
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress > 90) {
                    clearInterval(progressInterval);
                    progress = 90;
                }
                updateButtonProgress('optimizeBtn', 'optimizeProgress', Math.min(Math.round(progress), 90));
            }, 300);

            try {
                const response = await fetch('/optimize', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: originalText,
                        model: selectedModel,
                        instruction: instruction
                    })
                });

                const data = await response.json();
                if (data.error) {
                    throw new Error(data.error);
                }

                // 完成时
                clearInterval(progressInterval);
                updateButtonProgress('optimizeBtn', 'optimizeProgress', 100);
                document.getElementById('optimizedText').value = data.optimized_text;
            } catch (error) {
                clearInterval(progressInterval);
                updateButtonProgress('optimizeBtn', 'optimizeProgress', 0);
                console.error('Error:', error);
                alert('优化失败，请重试');
            } finally {
                button.disabled = false;
            }
        });

        // 修改显示优化按钮的代码部分
        // 在显示优化按钮的地方添加：
        document.getElementById('modelSelect').style.display = 'block';
        document.getElementById('instructionText').style.display = 'block';

        // 修改处理OCR结果的代码
        async function handleOCRResult(file) {
            try {
                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/ocr/', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                // 将OCR结果显示在可编辑的文本框中
                const outputText = document.getElementById('outputText');
                outputText.value = result.text.join('\n');
                
                // 显示优化相关的控件
                document.getElementById('modelSelect').style.display = 'block';
                document.getElementById('instructionText').style.display = 'block';
                document.getElementById('optimizeBtn').style.display = 'block';
                document.getElementById('optimizedText').style.display = 'block';
                
            } catch (error) {
                console.error('Error:', error);
                alert('OCR处理失败，请重试');
            }
        }
    </script>
</body>
</html>